var app = getApp();
var ajax = require('../../utils/ajax.js');
var util = require('../../utils/util.js');
var wxUtil = require('../../utils/wxUtil.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataLoaded: false,
    myHidden: true,
    modalHidden: true,
    addrList: [],
    addressId: "",
    name: '',
    tel: '',
    addr: '',
    province: '',
    city: '',
    county: '',
    provinceId: "",
    cityId: "",
    countyId: "",
    goodsId: '',
    skuId: '',
    amount: '',
    cartId: ''
  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    if (options.cartId) {
      this.setData({
        goodsId: JSON.parse(options.goodsId),
        skuId: JSON.parse(options.skuId),
        amount: JSON.parse(options.amount),
        cartId: JSON.parse(options.cartId),
        shop: app.getShop(),
      })
    } else {
      this.setData({
        goodsId: JSON.parse(options.goodsId),
        skuId: JSON.parse(options.skuId),
        amount: JSON.parse(options.amount),
        shop: app.getShop(),
        cartId: 0
      })
    }
  },
  onShow: function () {
    this._initAddr();
  },
  onShareAppMessage: function () {
    return {
      title: this.data.shop.shareTitle,
      path: "pages/index/index"
    }
  },
  /**
   * 初始化地址列表
   */
  _initAddr: function () {
    var _self = this;
    ajax.P('/openapi/CAddress/getAll', {}, function (data) {
      var d = data.result;
      console.log(data);
      if (d.data) {
        _self.setData({
          addrList: d.data
        })
      } else {
        _self.setData({
          addrList: d
        })
      }
      var addrList = _self.data.addrList;
      addrList.some(function (item) {
        if (item.isDefault == 1) {
          item.selected = true;
          _self.setData({
            addrList,
          })
        }
      })
      _self.setData({
        dataLoaded: true
      })
    })
  },
  /**
   * 选择地址
   */
  _select: function (e) {
    var _self = this;

    var index = parseInt(e.currentTarget.dataset.index);
    var addrList = this.data.addrList;
    addrList.forEach(function (item, index) {
      if (addrList[index].selected) {
        addrList[index].selected = false;
        _self.setData({
          addrList,
        })
      }
    })
    addrList[index].selected = true;
    console.log(addrList[index].selected)
    console.log(index);
    _self.setData({
      addressId: addrList[index].id,
      name: addrList[index].reName,
      tel: addrList[index].rePhone,
      addr: addrList[index].detailAddr,
      province: addrList[index].provinceName,
      city: addrList[index].cityName,
      county: addrList[index].districtName,
      addrList,
    })
    setTimeout(function () {
      wx.redirectTo({
        url: '../../pages/confirmOrder/confirmOrder?goodsId=' + _self.data.goodsId + '&skuId=' + _self.data.skuId + '&amount=' + _self.data.amount + '&cartId=' + _self.data.cartId + '&addressId=' + _self.data.addressId
      })
    }, 300)
  }
})